﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.BRL;
using BYFW.DAL;
using BYFW.BOL;
using System.Data;
using LDSP.Helper;

namespace LDSP.UI.EnterpriseAdmin
{
    public partial class MngEnterpriseUser : BRL.BaseEnterpriseAdminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    this.CheckQS();

                    this.InitDataDynamicBefore();
                    this.InitData();
                    this.GetCondition();
                    this.BindGrid();
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        /// <summary>
        /// 源文档ID
        /// </summary>
        protected int OwnerID
        {
            get { return this.GetVSInt("OwnerID"); }
            set
            {
                this.SetVS("OwnerID", value);
            }
        }

        /// <summary>
        /// 0，代表企业用户管理页面。
        /// 1，代表企业用户选择页面。
        /// </summary>
        protected string FormType
        {
            get
            {
                return this.GetVSString("formtype");
            }
            set
            {
                this.SetVS("formtype", value);
            }
        }

        protected int col_chb = 0;
        protected int col_idx = 1;
        protected int col_enterprise = 2;
        protected int col_user_code = 3;
        protected int col_user_name = 4;
        protected int col_is_valid = 5;
        protected int col_comment = 6;
        protected int col_update = 7;
        protected int col_delete = 8;

        protected void CheckQS()
        {
            OwnerID = this.GetInt(this.Request.QueryString["id"]);
            FormType = this.Request.QueryString["type"];
            PageID = this.Request.QueryString["PageID"];
        }

        /// <summary>
        /// 传入参数，设置过滤条件
        /// </summary>
        protected void SetSpecialPageInfo()
        {
            g_pageInfo.Direction = true;
            g_pageInfo.Sort = "code";
            g_pageInfo.PageSize = FormType == "1" ? 1000 : GetPageSizeSetting();
            g_pageInfo.PageIndex = this.grd_list.PageIndex;
        }

        protected void InitData()
        {
            this.SetSpecialPageInfo();

            BindDDLPageSize();
            if (FormType == "1")
            {
                this.hid_docIDs.Value = GetHidDocFormat(this.UserList(PageID));
            }

            this.btnOK.Visible = FormType == "1";//type==1，表示是用户选择页面。
            this.btn_delete.Visible = FormType == "0";//type==0,表示是用户管理页面。
            this.btn_add.Visible = FormType == "0";//type==0,表示是用户管理页面。
            this.ddl_pageSize.Visible = FormType == "0";//type==0,表示是用户管理页面。
        }

        private string GetHidDocFormat(string p)
        {
            string result = string.Empty;
            string[] ids = p.Split(';');
            foreach (string id in ids)
            {
                result += "," + id.Trim() + ",";
            }
            return result;
        }
        protected void InitDataDynamicBefore()
        {
            this.grd_list.Columns[col_update].Visible = FormType == "0";//type==0，表示是用户管理页面。
            this.grd_list.Columns[col_delete].Visible = FormType == "0";//type==0，表示是用户管理页面。

            this.grd_list.Columns[col_enterprise].Visible = IsEnterpriseGroupAdmin;
        }
        protected void BindDDLPageSize()
        {
            CommonControlInitial.InitialPageSize(this.ddl_pageSize);
            this.ddl_pageSize.SelectedValue = g_pageInfo.PageSize.ToString();
        }
        protected void BindGrid()
        {
            DataTable dt = BYFW.SFL.CommonOP.SortedTable(new EnterpriseUser().GetRecords(g_pageInfo.ConditionWhere, true), g_pageInfo.GetSortExpression());

            this.grd_list.PageSize = g_pageInfo.PageSize;
            this.grd_list.PageIndex = g_pageInfo.PageIndex;
            this.grd_list.DataSource = dt;
            this.grd_list.DataBind();

            SavePageSizeSetting();

            this.TotalRecords.Text = LDSP.Helper.StringUtil.GetSearchText(dt.Rows.Count); ;
        }

        protected void GetCondition()
        {
            string cond = "";
            if (this.txt_name.Text.Trim() != "")
            {
                cond += DefaultDB.GetSQLMultiCondition("code", EDataType.String, this.txt_name.Text.Trim(), true, true);
            }

            int enterpriseId = this.LoginUser.EnterpriseID;

            if (IsEnterpriseGroupAdmin)
            {
                //如果是集团用户，则搜索所有集团用户及子公司用户
                IList<Enterprise> enterprises = this.LoginUser.Enterprise.GetSubsidiaryList();
                string subdiaries = this.LoginUser.EnterpriseID + ";";
                foreach (Enterprise en in enterprises)
                {
                    subdiaries += en.ID + ";";
                }

                cond = this.AppendCondition(cond, DefaultDB.GetSQLInAndNotInCondition("enterpriseID", EDataType.Int, subdiaries.ToString(), true, false), true);
            }
            else
            {//如果是普通公司管理员，则只搜索自己公司的用户
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("enterpriseID", EDataType.Int, enterpriseId.ToString(), "=", true), true);
            }

            if (FormType != "1")
            {
                if (!IsEnterpriseGroupAdmin)
                {//如果是普通企业管理界面，则只可以管理普通用户
                    cond = this.AppendCondition(cond, new BaseEntity().DB.GetSQLNormalCondition("userType", EDataType.Int, "1", "=", true), true);//"1" 是普通管理员。
                }
            }

            g_pageInfo.Condition = cond;
        }

        protected void ddl_pageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                g_pageInfo.PageSize = this.GetInt(this.ddl_pageSize.SelectedValue);
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_add_Click(object sender, EventArgs e)
        {
            try
            {
                this.JSRedirect("AddEnterpriseUser.aspx", false);
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_delete_Click(object sender, EventArgs e)
        {
            try
            {
                this.DeleteCheckedInGrid<EnterpriseUser>(this.grd_list);
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_search_Click(object sender, EventArgs e)
        {
            try
            {
                this.GetCondition();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btnOK_Click(object sender, EventArgs e)
        {
            List<string> userIDs = new List<string>();
            foreach (GridViewRow row in this.grd_list.Rows)
            {
                CheckBox chb = (CheckBox)row.FindControl("chb");

                if (chb.Checked)
                {
                    string id = chb.Attributes["docid"];
                    userIDs.Add(id);
                }
            }

            this.UserList(PageID, this.CombineStrS(userIDs));
            this.JSCloseWindow();
        }

        protected void grd_list_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int id = this.GetInt(e.CommandArgument.ToString());
                if (e.CommandName == "updateItem")
                {
                    this.JSRedirect("AddEnterpriseUser.aspx?id=" + id, false);
                }
                else if (e.CommandName == "deleteItem")
                {
                    EnterpriseUser ett = new EnterpriseUser();
                    ett.GetProperties(id);
                    ett.IsValid = false;
                    ett.Update();

                    this.BindGrid();
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    EnterpriseUser ett = new EnterpriseUser();
                    ett.GetProperties(((DataRowView)e.Row.DataItem).Row);

                    this.ShowSequenceNumber(e.Row, 1);

                    CheckBox chb = (CheckBox)e.Row.FindControl("chb");
                    LinkButton lnk_update1 = (LinkButton)e.Row.FindControl("lnk_update");
                    LinkButton lnk_delete1 = (LinkButton)e.Row.FindControl("lnk_delete");

                    //设置勾选状态。
                    chb.Attributes["docid"] = ett.ID.ToString();
                    if (this.MultiPageIncludeCheckedId(this.hid_docIDs, ett.ID))
                    {
                        chb.Checked = true;
                    }

                    //设置修改，删除按钮状态
                    if (IsEnterpriseGroupAdmin && FormType == "1")
                    {//如果是集团用户且在用户选择页面
                        //禁止修改和删除
                        lnk_update1.OnClientClick = null;
                        lnk_update1.CommandName = null;
                        lnk_update1.Enabled = false;

                        lnk_delete1.OnClientClick = null;
                        lnk_delete1.CommandName = null;
                        lnk_delete1.Enabled = false;
                    }
                    else if (IsEnterpriseGroupAdmin && FormType == "0")
                    {//如果是集团用户且在用户管理页面
                        if (!ett.Enterprise.IsEnterpriseGroup)
                        {//如果本条数据不是集团用户，则禁止修改和删除
                            chb.Enabled = false;

                            lnk_update1.OnClientClick = null;
                            lnk_update1.CommandName = null;
                            lnk_update1.Enabled = false;

                            lnk_delete1.OnClientClick = null;
                            lnk_delete1.CommandName = null;
                            lnk_delete1.Enabled = false;
                        }
                    }

                    e.Row.Cells[col_enterprise].Text = ett.Enterprise.Code;
                    e.Row.Cells[col_is_valid].Text = ett.IsValid ? "是" : "否";
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                g_pageInfo.PageIndex = e.NewPageIndex;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (g_pageInfo.Sort == e.SortExpression)
                {
                    g_pageInfo.Direction = !g_pageInfo.Direction;
                }
                else
                {
                    g_pageInfo.Direction = true;
                }
                g_pageInfo.Sort = e.SortExpression;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
    }
}



